/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.repository;

import com.je.bpm.common.project.model.ProjectManifest;
import com.je.bpm.core.converter.converter.BpmnXMLConverter;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.impl.RepositoryServiceImpl;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.persistence.entity.DeploymentEntity;
import com.je.bpm.engine.impl.persistence.entity.ResourceEntity;
import com.je.bpm.engine.impl.persistence.entity.ResourceEntityManager;
import com.je.bpm.engine.impl.util.IoUtil;
import com.je.bpm.engine.impl.util.ReflectUtil;
import com.je.bpm.engine.repository.Deployment;
import com.je.bpm.engine.repository.DeploymentBuilder;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 *
 */
public class DeploymentBuilderImpl implements DeploymentBuilder, Serializable {

    private static final long serialVersionUID = 1L;
    protected static final String DEFAULT_ENCODING = "UTF-8";

    protected transient RepositoryServiceImpl repositoryService;
    protected transient ResourceEntityManager resourceEntityManager;

    protected DeploymentEntity deployment;
    protected boolean isBpmn20XsdValidationEnabled = true;
    protected boolean isProcessValidationEnabled = true;
    protected boolean isDuplicateFilterEnabled;
    protected Date processDefinitionsActivationDate;
    protected Map<String, Object> deploymentProperties = new HashMap<>();
    private ProjectManifest projectManifest;
    private Integer enforcedAppVersion;

    public DeploymentBuilderImpl(RepositoryServiceImpl repositoryService) {
        this(repositoryService,
                Context.getProcessEngineConfiguration().getDeploymentEntityManager().create(),
                Context.getProcessEngineConfiguration().getResourceEntityManager());
    }

    public DeploymentBuilderImpl(RepositoryServiceImpl repositoryService,
                                 DeploymentEntity deployment,
                                 ResourceEntityManager resourceEntityManager) {
        this.repositoryService = repositoryService;
        this.deployment = deployment;
        this.resourceEntityManager = resourceEntityManager;
    }

    @Override
    public DeploymentBuilder addInputStream(String resourceName, InputStream inputStream) {
        if (inputStream == null) {
            throw new ActivitiIllegalArgumentException("inputStream for resource '" + resourceName + "' is null");
        }
        byte[] bytes = IoUtil.readInputStream(inputStream, resourceName);
        ResourceEntity resource = resourceEntityManager.create();
        resource.setName(resourceName);
        resource.setBytes(bytes);
        deployment.addResource(resource);
        return this;
    }

    @Override
    public DeploymentBuilder setProjectManifest(ProjectManifest projectManifest) {
        this.projectManifest = projectManifest;
        return this;
    }

    public ProjectManifest getProjectManifest() {
        return this.projectManifest;
    }

    public boolean hasProjectManifestSet() {
        return this.projectManifest != null;
    }

    @Override
    public DeploymentBuilder setEnforcedAppVersion(Integer enforcedAppVersion) {
        this.enforcedAppVersion = enforcedAppVersion;
        return this;
    }

    public Integer getEnforcedAppVersion() {
        return this.enforcedAppVersion;
    }

    public boolean hasEnforcedAppVersion() {
        return this.enforcedAppVersion != null;
    }

    @Override
    public DeploymentBuilder addInputStream(String resourceName,
                                            Resource resource) {
        try {
            if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                try (ZipInputStream inputStream = new ZipInputStream(resource.getInputStream())) {
                    addZipInputStream(inputStream);
                }
            } else {
                try (InputStream inputStream = resource.getInputStream()) {
                    addInputStream(resourceName, inputStream);
                }
            }
        } catch (IOException e) {
            throw new ActivitiException("Couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
        }
        return this;
    }

    @Override
    public DeploymentBuilder addClasspathResource(String resource) {
        InputStream inputStream = ReflectUtil.getResourceAsStream(resource);
        if (inputStream == null) {
            throw new ActivitiIllegalArgumentException("resource '" + resource + "' not found");
        }
        return addInputStream(resource, inputStream);
    }

    @Override
    public DeploymentBuilder addString(String resourceName, String text) {
        if (text == null) {
            throw new ActivitiIllegalArgumentException("text is null");
        }
        ResourceEntity resource = resourceEntityManager.create();
        resource.setName(resourceName);
        try {
            resource.setBytes(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            throw new ActivitiException("Unable to get process bytes.", e);
        }
        deployment.addResource(resource);
        return this;
    }

    @Override
    public DeploymentBuilder addBytes(String resourceName, byte[] bytes) {
        if (bytes == null) {
            throw new ActivitiIllegalArgumentException("bytes is null");
        }
        ResourceEntity resource = resourceEntityManager.create();
        resource.setName(resourceName);
        resource.setBytes(bytes);

        deployment.addResource(resource);
        return this;
    }

    @Override
    public DeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
        try {
            ZipEntry entry = zipInputStream.getNextEntry();
            while (entry != null) {
                if (!entry.isDirectory()) {
                    String entryName = entry.getName();
                    byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName);
                    ResourceEntity resource = resourceEntityManager.create();
                    resource.setName(entryName);
                    resource.setBytes(bytes);
                    deployment.addResource(resource);
                }
                entry = zipInputStream.getNextEntry();
            }
        } catch (Exception e) {
            throw new ActivitiException("problem reading zip input stream", e);
        }
        return this;
    }

    @Override
    public DeploymentBuilder addBpmnModel(String resourceName, BpmnModel bpmnModel) {
        BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
        try {
            String bpmn20Xml = new String(bpmnXMLConverter.convertToXML(bpmnModel), "UTF-8");
            addString(resourceName, bpmn20Xml);
        } catch (UnsupportedEncodingException e) {
            throw new ActivitiException("Error while transforming BPMN model to xml: not UTF-8 encoded", e);
        }
        return this;
    }

    @Override
    public DeploymentBuilder name(String name) {
        deployment.setName(name);
        return this;
    }

    @Override
    public DeploymentBuilder category(String category) {
        deployment.setCategory(category);
        return this;
    }

    @Override
    public DeploymentBuilder key(String key) {
        deployment.setKey(key);
        return this;
    }

    @Override
    public DeploymentBuilder disableBpmnValidation() {
        this.isProcessValidationEnabled = false;
        return this;
    }

    @Override
    public DeploymentBuilder disableSchemaValidation() {
        this.isBpmn20XsdValidationEnabled = false;
        return this;
    }

    @Override
    public DeploymentBuilder tenantId(String tenantId) {
        deployment.setTenantId(tenantId);
        return this;
    }

    @Override
    public DeploymentBuilder enableDuplicateFiltering() {
        this.isDuplicateFilterEnabled = true;
        return this;
    }

    @Override
    public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
        this.processDefinitionsActivationDate = date;
        return this;
    }

    @Override
    public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
        deploymentProperties.put(propertyKey, propertyValue);
        return this;
    }

    @Override
    public Deployment deploy() {
        return repositoryService.deploy(this);
    }

    // getters and setters
    // //////////////////////////////////////////////////////

    public DeploymentEntity getDeployment() {
        return deployment;
    }

    public boolean isProcessValidationEnabled() {
        return isProcessValidationEnabled;
    }

    public boolean isBpmn20XsdValidationEnabled() {
        return isBpmn20XsdValidationEnabled;
    }

    public boolean isDuplicateFilterEnabled() {
        return isDuplicateFilterEnabled;
    }

    public Date getProcessDefinitionsActivationDate() {
        return processDefinitionsActivationDate;
    }

    public Map<String, Object> getDeploymentProperties() {
        return deploymentProperties;
    }

}
